package C8_7_ChangeUnidirectionalAssociationToBidirectional;

import C8_2_ReplaceDataValueWithObject.C8_2_demo;

import java.util.HashSet;
import java.util.Set;

/**
 * Desc:&emsp;&ensp;将单项关联改为双项关联<br/>
 * 使用反向指针实现双向关联
 * @author 李渊&emsp;
 * @version 1.0
 * @since V4.3&emsp;2022/7/13
 */
public class C8_7_demo {
    //==========重构前===========
    // 客户
    class Cus{
        private final String name;

        public Cus(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
    // 订单类
    class Order{
        // 客户
        private Cus _cus;

        public Cus get_cus() {
            return _cus;
        }

        public void set_cus(Cus _cus) {
            this._cus = _cus;
        }
    }

    //==========重构后===========
    // 客户
    class Cus_1{
        private final String name;
        // 第一步，一个客户出现在多份订单中，记录反向引用
        private Set _orders = new HashSet();

        public Cus_1(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        //第二步，添加辅助函数
        protected Set friendOrders(){
            return _orders;
        }
    }
    // 订单类
    class Order_1{
        // 客户
        private Cus_1 _cus;

        public Order_1(Cus_1 _cus) {
            this._cus = _cus;
        }

        public Cus_1 get_cus() {
            return _cus;
        }

        // 第三步、修改setter，同时更新反向指针
        public void set_cus(Cus_1 arg) {
            if(this._cus!=null)
                this._cus.friendOrders().remove(this);
            this._cus = arg;
            if(this._cus!=null)
                this._cus.friendOrders().add(this);
        }
    }
}
